package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.ProcessContent;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MessageUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.widget.CheckLineView;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;

public class WorkprocessConvertFragment extends BaseFragment implements OnClickListener {

  public static final String EXTRA_VALUE = "com.isunland.managesystem.ui.EXTRA_VALUE";
  private static final int REQUEST_ACQUIRE_FINISHTIME = 0;
  private static final int REQUEST_EXECUTOR = 1;
  /** 站内通知 */
  @BindView(R.id.clv_instationNotify) CheckLineView clvInstationNotify;
  /** 短信通知 */
  @BindView(R.id.clv_SMSNotify) CheckLineView clvSMSNotify;
  @BindView(R.id.clv_notifyAllParticipant) CheckLineView clvNotifyAllParticipant;
  private String mPlanId;// 计划id
  //private String mPanRequestTime;// 要求完成时间
  private TextView mtv_executor_workConvert;// 执行人
  private TextView mtv_completeTime_workConvert;// 要求完成时间
  /** 要求完成时间 */
  private String mAcquireTime;
  private String mExecuteName; // 执行人的姓名
  private String mExecuteJobN;// 执行人JOBN
  private BaseVolleyActivity mActicity;
  private ProcessContent mProcessContent;

  public static Fragment newInstance(ProcessContent processContent) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_VALUE, processContent);
    WorkprocessConvertFragment fragment = new WorkprocessConvertFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitleCustom(R.string.taskConvert);
    mProcessContent = (ProcessContent) getArguments().getSerializable(EXTRA_VALUE);
    if (mProcessContent != null) {
      mPlanId = mProcessContent.getId();
    } else {
      mProcessContent = new ProcessContent();
    }
    mActicity = (BaseVolleyActivity) getActivity();
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_work_convert, container, false);
    ButterKnife.bind(this, view);
    mtv_executor_workConvert = (TextView) view.findViewById(R.id.tv_executor_workConvert);
    mtv_completeTime_workConvert = (TextView) view.findViewById(R.id.tv_completeTime_workConvert);

    mtv_executor_workConvert.setOnClickListener(this);
    mtv_completeTime_workConvert.setOnClickListener(this);
    clvInstationNotify.getCbCheck()
        .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
          @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked && clvNotifyAllParticipant.getCbCheck().isChecked()) {
              clvNotifyAllParticipant.getCbCheck().setChecked(false);
            }
          }
        });
    clvNotifyAllParticipant.getCbCheck()
        .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
          @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked && clvInstationNotify.getCbCheck().isChecked()) {
              clvInstationNotify.getCbCheck().setChecked(false);
            }
          }
        });
    return view;
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_confirm, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  // 响应返回按钮
  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      // 提交
      case R.id.menu_item_confirm:
        volleyPostSaveCheck();
        break;
      default:
        return super.onOptionsItemSelected(item);
    }
    return super.onOptionsItemSelected(item);
  }

  private void volleyPostSaveCheck() {
    if (MyUtils.isEmptyText(mtv_completeTime_workConvert)) {
      Toast.makeText(getActivity(), R.string.completeTime, Toast.LENGTH_SHORT).show();
      return;
    }

    if (MyUtils.isEmptyText(mtv_executor_workConvert)) {
      Toast.makeText(getActivity(), R.string.completeExecutor, Toast.LENGTH_SHORT).show();
      return;
    }

    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
    dialog.setTitle(R.string.restart_title);
    dialog.setMessage(R.string.cannotEdit);
    dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        volleyPostSave();
      }
    });

    dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
      }
    });
    dialog.create().show();
  }

  private void volleyPostSave() {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingSubmit);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_WORK_CONVERT);
    HashMap<String, String> params = new HashMap<>();

    params.put("id", mPlanId);
    if (mExecuteJobN != null) {
      params.put("excManId", mExecuteJobN);
    }
    if (mExecuteName != null) {
      params.put("excManName", mExecuteName);
    }

    if (mAcquireTime != null) {
      params.put("date", mAcquireTime);
    }
    mActicity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        Toast.makeText(getActivity(), R.string.convertSuccess, Toast.LENGTH_SHORT).show();
        getActivity().setResult(Activity.RESULT_OK);

        if (clvInstationNotify.getCbCheck().isChecked()) {
          String content = getString(R.string.newWorkMessage, getString(R.string.convert));
          LogUtil.i("content=", content);
          MessageUtil.sendReport(mActivity, mExecuteJobN, mExecuteName, content);
        }
        if (clvSMSNotify.getCbCheck().isChecked()) {
          String content = getString(R.string.newWorkMessage, getString(R.string.convert));
          LogUtil.i("content=", content);
          MessageUtil.sendSMS(mActivity, mExecuteJobN, content);
        }
        if (clvNotifyAllParticipant.getCbCheck().isChecked()) {

          String content = getString(R.string.newWorkMessage, getString(R.string.convert));
          //通知所有人
          String excManNames = mProcessContent.getExcManName();
          String coopManNames = mProcessContent.getCoopManNames();
          String excManJobNOs = mProcessContent.getExcManId();
          String coopManIds = mProcessContent.getCoopManIds();
          MessageUtil.sendReport(mActivity,
              MyStringUtil.connect(excManJobNOs, getString(R.string.comma), coopManIds),
              MyStringUtil.connect(excManNames, getString(R.string.comma), coopManNames), content);
        }
        MyUtils.dismissDialog();
        Intent intent = new Intent(getActivity(), WorkProcessListActivity.class);
        startActivity(intent);
        getActivity().finish();
      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), R.string.convertFail, Toast.LENGTH_SHORT).show();
        LogUtil.e("" + arg0);
      }
    });
    LogUtil.i("params" + params);
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {
      // 添加执行人
      case R.id.tv_executor_workConvert:
        showDialog(REQUEST_EXECUTOR, null);
        break;

      // 添加要求完成时间
      case R.id.tv_completeTime_workConvert:
        showDialog(REQUEST_ACQUIRE_FINISHTIME, new Date());
        break;

      default:
        break;
    }
  }

  /**
   * 显示时间对话框
   *
   * @param requestCode 请求码
   * @param date 对话框初始显示时间
   */
  @SuppressWarnings("UnusedParameters") public void showDialog(int requestCode, Date date) {
    DialogFragment dialog = null;

    switch (requestCode) {
      case REQUEST_ACQUIRE_FINISHTIME:
        dialog = new BaseYMDTimeDialogFragment();
        break;
      case REQUEST_EXECUTOR:
        Intent i = new Intent(getActivity(), AppointerListActivity.class);
        startActivityForResult(i, requestCode);
        return;
      default:
        break;
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    if (dialog == null) return;
    dialog.setTargetFragment(WorkprocessConvertFragment.this, requestCode);
    dialog.show(fm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_ACQUIRE_FINISHTIME && data != null) {
      Date acquireDate = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      // mAcquireTime = MyDateUtil.dateToString(acquireDate);
      //noinspection deprecation
      mAcquireTime = MyDateUtil.dateToString(acquireDate, MyDateUtil.TYPE_DATE);
      mtv_completeTime_workConvert.setText(mAcquireTime);
      return;
    }

    if (requestCode == REQUEST_EXECUTOR && data != null) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      mExecuteName = customer.getName();
      mExecuteJobN = customer.getId();
      LogUtil.i("mExecuteName<><>" + mExecuteName);
      LogUtil.i("mExecuteJobN<><>" + mExecuteJobN);
      mtv_executor_workConvert.setText(mExecuteName);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}
